package com.example.w.service.impl;

import com.example.w.common.exception.SystemException;
import com.example.w.common.pattern.PricingStrategy;
import com.example.w.common.pojo.Order;
import com.example.w.common.pojo.Payment;
import com.example.w.common.pojo.Table;
import com.example.w.common.util.PaymentHandler;
import com.example.w.dao.OrderDao;
import com.example.w.dao.PaymentDao;
import com.example.w.dao.TableDao;
import com.example.w.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

@Service
@Transactional
public class PaymentServiceImpl implements PaymentService {

    PaymentHandler paymentHandler = new PaymentHandler();
    @Autowired
    PaymentDao paymentDao;
    @Autowired
    OrderDao orderDao;
    @Autowired
    TableDao tableDao;
    @Value("${pricingStrategy.strategyName}")
    String strategyName;     //策略选择
    @Autowired
    ApplicationContext applicationContext;

    /**
     * 根据订单id和支付方式进行支付，调用相应支付接口
     * @param orderId 订单id
     * @param paymentType 支付方式，0：现金，1：微信，2：支付宝，3：银行卡
     * @return 支付结果
     */
    @Override
    public Payment pay(Long orderId, int paymentType) {
        Order order;    //记录对应订单
        //使用orderDao检查该订单是否存在，检查订单支付状态
        order = orderDao.selectByPrimaryKey(orderId);
        if (order == null) {
            throw new SystemException("该订单不存在");
        }else if (order.isPaid()) {
            throw new SystemException("该订单已完成支付");
        }
        //获取支付策略
        PricingStrategy pricingStrategy =
                applicationContext.getBean(strategyName, PricingStrategy.class);
        //获取应付款金额
        BigDecimal total_amount = pricingStrategy.getPricingTotal(order);

        //TODO 获取当前登录用户id
        //获取id
        Long cashierId = 0L;

        Map<String, Object> payResult =
                paymentHandler.payForOrder(total_amount, paymentType, order.getId());
        Payment payment = new Payment(
                orderId,
                (BigDecimal)payResult.get("amount"),
                paymentType,
                (String)payResult.get("serialNumber"),
                (Date)payResult.get("time"),
                cashierId);
        paymentDao.insertSelective(payment);

        //修改订单状态
        order.setPaystatus(1);
        orderDao.updateByPrimaryKeySelective(order);

        return payment;
    }
}
